import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { CommonService } from '../../../../services/common.service'
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';

interface DataItem {
  update_time: any;
  upload_time: any;
  file_size: any;
  status: any;
}
@Component({
  selector: 'app-contractextractiondata',
  templateUrl: './contractextractiondata.component.html',
  styleUrls: ['./contractextractiondata.component.css']
})
export class ContractextractiondataComponent implements OnInit {
  //文件列表
  public listOfFileData: any = [
  ];
  editId: string | null = null;
  isVisible = false;
  isAddFileVisible = false;
  // 新增标签数量
  tagsList: any = [
    {
      addTagsList: [{ value: '' }]
    }
  ];
  // 标签列表
  TagList: any = [
  ];
  // 搜索标签列表的value
  seekTagValue: any = null
  TagListOne: any = null
  tagListForResult: any[] = [];
  // 编辑名称
  EditLabelName: any = '';
  // 文件内容
  fileListData: any = [{
    result: {
      catalog: [
        {
          children_nodes: [
            {
              children_nodes: [],
              location: [
                [288, 478],
                [766, 478],
                [766, 515],
                [288, 515]
              ],
              node_depth: 2,
              node_text: "(一) 私募基金的名称",
              page: 11
            }
          ],
          location: [
            [288, 458],
            [766, 458],
            [766, 495],
            [288, 495]
          ],
          node_depth: 1,
          node_text: "第四节 私募基金的基本情况",
          page: 11
        },
        {
          children_nodes: [],
          location: [
            [288, 458],
            [766, 458],
            [766, 495],
            [288, 495]
          ],
          node_depth: 1,
          node_text: "第五节 私募基金的募集",
          page: 12
        }
      ],
      content_base64: "",
      content_size: 436,
      file_id: "8d260b4a-a988-11eb-891e-054b005f5867",
      file_name: "歌斐诺宝曼仕宏量2号趋势策略私募证券投资基金基金合同.pdf",
      file_type: "pdf"
    }
  }];
  //文件的标签标注结果
  fileTagData: any = [];
  dataStep: number = 1;
  // 项目id
  itemId: '';
  // 通过标注按钮拿到的文件id
  markId: '';
  // 删除标签拿到的当前id
  deleteTagId: '';
  // 删除标签的模态框
  deleteTagShow = false;
  // 删除文件拿到的id
  deletefileId: '';
  // 删除文件的模态框
  deleteFileShow = false;
  //navOne
  navOnes = true;
  //navTwo
  navTwos = false;
  //navThree
  navThrees = false;
  //navFour
  navFours = false;
  //标注状态点击框
  statusVisable = false;
  // 剩余可创建标签长度
  TagLength: number = 0;
  //PDF
  pdfData: any[] = [];
  pdfSize: any[] = []; // pdf的大小
  displayList: []// 要素展示数据
  highlight: any[] = []; // 高亮展示数据
  //添加文件选择框是否展现
  projectBoxShow: boolean = false
  //删除所有弹出框
  deleteAllShow: boolean = false;
  //取消所有弹出框
  cancelAllShow: boolean = false;
  //重试所有弹出框
  restartAllShow: boolean = false;

  //上传列表
  public uploadFileList: any[] = [];
  //轮询定时器
  jobTimer: any = null;
  fileTimer: any = null; //文件轮询定时器
  //临时存储file
  currFile: any = {
    file_name: ""
  };
  // 搜索文件Data
  seekFileList:any=null
  // 搜索文件输入框Value
  seekFileValue:any=null
  // txt
  txtData: any = "";
  isSpinning: boolean = true;
  targetPage: number = 0; //跳转页面
  currentPage: number = 0; //当前页面-用于PDF展,从1开始
  currPaginationPage: number = 0; //用于分页控件，从0开始
  allPages: number = 0;//PDF 总页数
  public analyzeLabelResultOriginal: any = null; //原始标注结果评估内容
  public analyzeLabelResult: any = {
    label_result: [{
      values: []
    }]
  };
  // 搜索标注内容的value
  seekContenValue:any=null
  // 搜索内容的list
  seekContenList:any=null
  //处理后的标注结果评估内容
  currTagResIndex: number = 0;
  chartOpt: any;
  pieChart: any = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '2%',
      left: 'center',
      icon: 'circle'
    },
    series: [
      {
        type: 'pie',
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2
        }, radius: '70%',
        label: {
          show: false,
          position: 'center'
        },
        labelLine: {
          show: false
        },
        color: ['#5E7CE0', '#6CBFFF'],
        data: [
          { value: 0, name: '命中文件数' },
          { value: 0, name: '未命中文件数' }
        ]
      }
    ]
  }
  // 标注结果评估
  // 搜索标签名称value
  seekTagTwoValue:any=null
  // 搜索的标签列表
  seekTagTwoList:any=null

  public isCanDraw: boolean = false;
  public currBlock: any = {};
  fileType: string = ''; //文件类型 txt、pdf、word

  currScale: number = 1;//当前缩放比
  targetScale: number = 1; //目标缩放比

  timeCompare = (a: DataItem, b: DataItem) => {
    // console.log(a)
    return Date.parse(a.upload_time) - Date.parse(b.upload_time)
  };
  createTimeCompare = (a: DataItem, b: DataItem) => {
    return Date.parse(a.update_time) - Date.parse(b.update_time)
  };
  fontSizeCompare = (a: DataItem, b: DataItem) => {
    // console.log(a)
    return parseInt(a.file_size) - parseInt(b.file_size)
  };
  fileFilterFn = (status: any, item: DataItem) => item.status == status


  constructor(
    public http: CommonService,
    private route: ActivatedRoute,
    private message: NzMessageService,
    private modal: NzModalService,
    private viewContainerRef: ViewContainerRef) { }


  ngOnInit(): void {
    // 接收本地存储的项目id
    // let value = sessionStorage.getItem('id');
    // 获取标签列表
    this.getTagList();
    // 获取文件列表
    this.getFileList();
  }

  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    if (this.jobTimer != null) {
      clearInterval(this.jobTimer);
    }

    if (this.fileTimer != null) {
      clearInterval(this.fileTimer);
    }
  }


  onChartInit(event) {
    this.chartOpt = event;
  }

  //获取PDF
  getPDFData() {
    this.http.getPDFdata().then((res: any) => {
      console.log(res);
      if (res && res.file_type == "txt") {
        this.pdfData = res.content_base64;
        this.fileType = res.file_type;
        // console.log(this.txtData)
      } else if (res && res.file_type == "pdf") {
        this.pdfSize = res.page_size
        console.log(this.pdfSize);
        this.pdfData = [res.content_base64] // PDF的数据
        // this.pdfSize = res.page_size // pdf的大小
        this.fileType = res.file_type;
      }
      // this.pdfData = [res.content_base64] // PDF的数据
      // this.pdfSize = res.content_size // pdf的大小
      // this.displayList = this.dealData(res.result) // 要素展示
      // res.result.map((item: any) => {
      //   if (item.highlights && item.highlights.length > 0) {
      //     this.highlight.push(item.highlights)
      //   }
      // })
    })
  }

  // 获取标签列表
  getTagList(): void {
    if(this.seekTagValue){
      this.seekTagValue = ''
    }
    // 接收本地存储的项目id
    let itemId = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/data-mgr/query-all-label', {
      project_id: itemId
    }).then((res: any) => {
      if(res && res.result !=''){
        this.TagList = res.result
        // 搜索的data
        this.TagListOne = res.result
        let length = 100;
        this.TagLength = length;
        if (this.TagLength === 100) {
          // 计算剩余可以创建的标签
          this.TagLength = this.TagLength - this.TagList.length;
          console.log(this.TagList.length)
        }
      }else{
        this.message.error("标签列表为空!")
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })

  }
  // 搜索标签列表
  seekTag() {
    this.seekTagValue = this.seekTagValue.replace(/^\s+|\s+$/g,"")
    // console.log(typeof(this.`seekTagValue`))
    this.TagList = this.TagListOne
    let arr = [];
    this.TagList.forEach(e => {
      if (e.label_name.includes(this.seekTagValue)) {
        console.log(e)
        arr.push(e)
      }
    });
    // console.log(this.TagList)
    if (this.seekTagValue == '') {
      this.TagList = this.TagListOne
    } else {
      this.TagList = arr
    }
  }

  // 点击编辑按钮
  startEdit(data): void {
    console.log(data);
    this.EditLabelName = data.label_name;
    this.editId = data.label_id;
  }
  // 编辑标签name
  stopEdit(id): void {
    this.EditLabelName = this.EditLabelName.replace(/^\s+|\s+$/g,"")
    let newArray = this.TagList.map(e => {
      if(e.label_id != id)
      return e.label_name
    });
    if (newArray.includes(this.EditLabelName)) {
      this.message.error(this.EditLabelName + '已经存在!');
      return;
    }
    this.editId = null;
    if (this.EditLabelName === '' ? this.message.error('编辑名称不能为空') : '') {
    } else {
      this.http.post('/contract-extraction/data-mgr/update-label', {
        label_id: id,
        label_name: this.EditLabelName
      }).then((res: any) => {
        console.log(res)
        // 获取标签列表
        this.getTagList()
      }).catch((err: any) => {
        this.message.error(err.error_msg)
      })
    }
  }
  // 删除标签
  deleteTag(e) {
    this.deleteTagShow = true;
    this.deleteTagId = e;
  }
  // 取消删除标签
  deleteTagShut() {
    this.deleteTagShow = false;
  }
  // 确认删除标签
  deleteTagOk() {
    this.http.post('/contract-extraction/data-mgr/delete-label', {
      label_id: this.deleteTagId
    }).then((res: any) => {
      console.log(res)
      // 获取标签列表
      this.getTagList();
      this.deleteTagShow = false;
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  // 添加标签
  addTagsOk(): void {
    console.log(this.tagsList[0].addTagsList[0].value)
    let isNull = false;
    let isreturn = false;
    
    this.tagsList[0].addTagsList.forEach(i => {
      // 删除空格
      i.value = i.value.replace(/^\s+|\s+$/g,"")
      let newArray = this.TagList.map(e => e.label_name);
      if (newArray.includes(i.value)) {
       this.message.error(i.value + '已经存在!');
        isreturn = true;
        return;
      }
      if (i.value === '') {
        isNull = true;
        return;
      }
    });
    if (isNull) {
      this.message.error('标签内容不能为空!')
      return;
    }
    let arr: any = [];
    this.tagsList[0].addTagsList.forEach((i) => {
      arr.push(i.value)
    })
    arr.join()
    if (isreturn == false) {
      if (this.tagsList[0].addTagsList.length < 100) {
        // 接收本地存储的项目id
        let itemId = sessionStorage.getItem('id');
        this.http.post('/contract-extraction/data-mgr/add-label', {
          project_id: itemId,
          labels: arr
        }).then((res: any) => {
          console.log(res)
          //获取标签列表
          this.getTagList();
          // 关闭model
          this.isVisible = false;
        }).catch((err: any) => {
          this.message.error(err.error_msg)
        })
      } else {
        this.message.error('最多可以创建100个标签!');
      }
    }
  }
  //新建标签模态框点击取消
  addTagsCancel(): void {
    this.isVisible = false
  }
  // 获取文件列表
  getFileList() {
    if(this.seekFileValue){
      this.seekFileValue = ''
    }
    // 接收本地存储的项目id
    const that = this;
    let itemId = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/data-mgr/query-all-file', {
      project_id: itemId
    }).then((res: any) => {
      if(res && res.result != ''){
        console.log(res)
        // 将后台拿到的数据赋值给文件列表Data
        this.listOfFileData = res.result
        this.seekFileList = res.result
        if (that.listOfFileData.length > 0) {
          that.currFile = that.listOfFileData[0];
        }
      }else{
        this.message.error("文件列表为空!")
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  // 搜索文件列表
  seekFile(){
    this.seekFileValue = this.seekFileValue.replace(/^\s+|\s+$/g,"")
    this.listOfFileData = this.seekFileList
    let arr = [];
    console.log(this.seekFileValue)
    this.listOfFileData.forEach(e => {
      if(e.file_name.includes(this.seekFileValue)){
        arr.push(e)
      }
    });
    if(this.seekFileValue==''){
      this.listOfFileData = this.seekFileList
     }else{
       this.listOfFileData = arr
     }
  }
  // 删除文件
  deleteFile(e) {
    this.deletefileId = e;
    this.deleteFileShow = true;
  }
  // 取消删除文件
  deleteFileShut() {
    this.deleteFileShow = false;
    this.deleteAllShow = false
    this.cancelAllShow = false
    this.restartAllShow = false
  }
  // 确认删除文件
  deleteFileOk() {
    this.http.post('/contract-extraction/data-mgr/delete-file', {
      file_id: this.deletefileId
    }).then((res: any) => {
      console.log(res)
      // 获取文件列表
      this.getFileList();
      this.deleteFileShow = false;
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  // 标注按钮
  markFile(fileId) {
    // this.markId = e;
    console.log(fileId)
    let isFind = false;
    for (let i = 0; i < this.listOfFileData.length; i++) {
      if (fileId == this.listOfFileData[i].file_id) {
        isFind = true;
        this.currFile = this.listOfFileData[i];
      }
    }
    if (!isFind) {
      this.message.error("文件出错了，请刷新后重新选择文件！")
      return;
    }
    console.log(this.currFile);
    // 跳转人工标注页
    this.dataStep = 3
    this.navThrees = true
    this.getFileData();
    this.queryAllResult();
  }
  // 获取文件内容
  getFileData() {
    let that = this;
    this.http.post('/contract-extraction/data-mgr/query-file-content', {
      file_id: this.currFile.file_id
    }).then((res: any) => {
      console.log(res)
      let result = res.result;
      if ("job_id" in result) {
        console.log("存在Job_id");
        that.getFileDataByJob(result.job_id);
      } else {
        console.log("不存在Job_id");
        that.fileListData = res.result
        //这是实际接口 -- 测试时，需要注销
        that.pdfData = [that.fileListData.content_base64];
        that.pdfSize = that.fileListData.page_size; // pdf的大小
        that.fileType = that.fileListData.file_type;
        //注销结束
        setTimeout(() => {
          that.isSpinning = false;
        }, 2000);

      }


    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
    // console.log(this.fileListData)
  }

  // 获取文件的标签标注结果
  queryAllResult() {
    // console.log(this.markId)
    let that = this;
    this.http.post('/contract-extraction/data-mgr/query-file-result', {
      file_id: that.currFile.file_id
    }).then((res: any) => {

      that.fileTagData = res.result;
      if (that.fileType == 'pdf')
        that.updateHighBlocks();
      else if (that.fileType == 'txt') {
        that.updateTxTBlocks();
      }



      // that.fileTagData.map((item: any) => {
      //   console.log(item);
      //   item.values.map((item2: any) => {
      //     if (item2.blocks && item.blocks.length > 0) {
      //       that.highlight.push(item.blocks)
      //     }
      //   })
      // })
      // res.result.map((item: any) => {
      //   if (item.highlights && item.highlights.length > 0) {
      //     this.highlight.push(item.highlights)
      //   }
      // })

    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  //更新高亮元素
  updateHighBlocks() {
    let that = this;
    that.highlight = []
    console.log("updateHighBlocks");
    that.fileTagData.forEach((item: any) => {
      if (item.values) {
        item.values.forEach((item2: any) => {
          console.log(item2);
          if (item2.blocks && item2.blocks.length > 0) {
            that.highlight.push(item2.blocks)
          }
        })
      }
    });

    that.highlight = [...that.highlight]
    console.log(that.highlight)
  }

  //处理txt选择框
  updateTxTBlocks() {
    let that = this;
    that.highlight = []
    that.fileTagData.forEach((item: any) => {
      item.values.forEach((item2: any) => {
        if (item2.blocks && item2.blocks.length > 0) {
          that.highlight.push(item2.blocks)
        }
      })
    });

    that.highlight = [...that.highlight]
  }

  // 删除标注结果(删除指定value值）废弃
  deleteValue(e) {
    let resultId = e;
    this.http.post('/contract-extraction/data-mgr/delete-value', {
      result_id: resultId
    }).then((res: any) => {
      console.log(res)
      //获取文件的标签标注结果
      this.queryAllResult()
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  // 删除标签标注结果  废弃
  // deleteResult(e){
  //   let resultId = e;
  //   this.http.post('/contract-extract-tool/data-mgr/delete-value',{
  //     result_id:resultId
  //   }).then((res:any)=>{
  //     console.log(res)
  //     //获取文件的标签标注结果
  //     this.getFileTagData()
  //   })
  // }
  //获取标注结果评估内容
  getAnalyzeLabel(index, labelId) {
    const that = this;
    let itemId = sessionStorage.getItem('id') ? sessionStorage.getItem('id') : '';
    that.currTagResIndex = index;
    this.http.post('/contract-extraction/data-mgr/analyze-label', {
      project_id: itemId,
      label_id: labelId,
    }).then((res: any) => {
      console.log(res);
      this.analyzeLabelResultOriginal = res.result;
      this.analyzeLabelResult = this.analyzeLabelResultOriginal;
      // 搜索的list
      this.seekContenList = res.result.label_result;
      this.pieChart.series[0].data[0].value = this.analyzeLabelResultOriginal.hit_file_num;
      this.pieChart.series[0].data[1].value = this.analyzeLabelResultOriginal.no_hit_file_num;
      this.pieChart.series = [...this.pieChart.series]

      this.chartOpt.setOption(this.pieChart, true);
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  // 搜索标签结果
  seekContent(){
    this.seekContenValue = this.seekContenValue.replace(/^\s+|\s+$/g,"")
    this.analyzeLabelResult.label_result = this.seekContenList
    let arr = []
    this.analyzeLabelResult.label_result.forEach(e => {
      // console.log(e)
      if(e.file_name.includes(this.seekContenValue)){
        arr.push(e)
      }
    });
    if(this.seekContenValue == ''){
      this.analyzeLabelResult.label_result = this.seekContenList
    }else{
      this.analyzeLabelResult.label_result = arr
    }
  }
  // 刷新标注结果
  refreshData(){
    this.seekContenValue = ''
    this.analyzeLabelResult.label_result = this.seekContenList
  }
  addFileValue(itemIndex) {
    if (!this.fileTagData[itemIndex].values) {
      this.fileTagData[itemIndex].values = [];
    }
    this.fileTagData[itemIndex].values.push({});
  }

  deleteBlocks(itemIndex, blocksIndex) {
    this.fileTagData[itemIndex].values.splice(blocksIndex, 1)
  }

  // 点击添加标签的弹窗
  showModal(): void {
    //每次进来恢复初始状态,清空输入框  
    this.tagsList[0].addTagsList.length = 1;
    this.tagsList[0].addTagsList[0].value = '';
    this.isVisible = true;
  }

  handleOk(): void {
    console.log('Button ok clicked!');
    this.isVisible = false;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
    this.isAddFileVisible = false;
  }

  addTags(index) {
    console.log(this.tagsList[0].addTagsList[0].value)
    console.log(this.tagsList[index].addTagsList)
    console.log(index)
    if (this.tagsList[0].addTagsList.length < 100) {
      this.tagsList[index].addTagsList.push({ value: '' })
    } else {
      this.message.error("最多可以创建100个标签!")
    }

  }
  //显示添加文件modal
  showAddFileModal(): void {
    this.isAddFileVisible = true
  }
  //添加文件模态框确定
  addFileOk() {
    this.isAddFileVisible = false
  }
  //添加文件模态框取消
  addFileCancel() {
    this.isAddFileVisible = false
  }
  //标注状态点击框
  statusClick() {
    this.statusVisable = true
  }
  //标注状态点击按钮
  statusClickBtn() {
    this.statusVisable = false
  }
  //1
  navOne(e) {
    this.dataStep = e;
    this.navOnes = true;
    console.log(e)
    console.log(this.dataStep)
    //  当再次点击1的时候 将其他导航条失去高亮
    this.navTwos = false;
    this.navThrees = false;
    this.navFours = false;
  }
  //2
  navTwo(e) {
    if (this.navOnes === true) {
      this.dataStep = e;
      this.navTwos = true;
      // 从3点击2了 就把3和4的高亮取消掉
      this.navThrees = false;
      this.navFours = false;
      this.getFileList();
      if (this.jobTimer != null) {
        clearInterval(this.jobTimer)
      }
    } else {
      return
    }
  }
  //3
  navThree(e) {
    if (this.navTwos == true && this.listOfFileData.length > 0) {
      this.dataStep = e;
      this.navThrees = true;
      // 从4点击3了 就把4的高亮取消掉
      this.navFours = false;
      //获取PDF--测试时需要放开
      // this.getPDFData();
      // 获取文件内容
      this.getFileData();
      this.queryAllResult();

    } else if (this.listOfFileData.length == 0) {
      this.message.error("请先上传文件！");
      return
    } else {
      this.message.error("请先操作前面步骤！");
      return
    }
  }
  // 4
  navFour(e) {
    if (this.navThrees === true) {
      this.dataStep = e;
      if (this.jobTimer != null) {
        clearInterval(this.jobTimer)
      }
      this.navFours = true;
      // 将标签列表重新赋值
      this.tagListForResult = this.TagList;
      this.getAnalyzeLabel(0, this.tagListForResult[0].label_id);
    } else {
      return
    }
  }
  // 搜索标签名称
  seekTagTwo(){
    this.seekTagTwoValue = this.seekTagTwoValue.replace(/^\s+|\s+$/g,"")
    this.tagListForResult = this.TagListOne
    let arr = []
    this.tagListForResult.forEach(e => {
      if(e.label_name.includes(this.seekTagTwoValue)){
        arr.push(e)
      }
    });
    if(this.seekTagTwoValue == ''){
      this.tagListForResult = this.TagListOne
    }else{
      this.tagListForResult = arr
    }
  }

  //鼠标离开时间
  mouseleave() {
    this.projectBoxShow = false;
  }

  //展示选择文件框
  showAddProjectBox() {
    this.projectBoxShow = true;
  }

  getFile(e) {
    console.log(e);
    let that = this;
    let files = e.target.files[0];
    let newFile: any = {}
    let fileName = files.name;
    let fileSize = (files.size / 1024 / 1024).toFixed(3);
    let status = "running"
    var reader = new FileReader();
    reader.readAsDataURL(files);
    reader.onload = function () {
      console.log(reader.result); //获取到base64格式图片
      newFile.file_name = fileName;
      newFile.fileSize = fileSize;
      let file64 = reader.result.toString();
      newFile.file_base64 = file64.substring(file64.indexOf(',') + 1);
      newFile.status = status;
      that.uploadFileList.push(newFile)
      that.uploadFileList = [...that.uploadFileList]
      that.uploadFileTask();
    };
    that.isAddFileVisible = true;
  }

  //文件夹选择--文件转化成base64时，是异步转化，
  async getFileFolder(e) {
    console.log(e);
    let that = this;
    let files = e.target.files
    const readFileAsync = file => new Promise(resolve => {
      const reader = new FileReader()
      reader.onload = evt => resolve(evt.target.result.toString)
      reader.readAsDataURL(file)
    })

    for (let i = 0; i < files.length; i++) {
      let file = files[i];
      let newFile: any = {}
      let fileName = file.name;
      let fileSize = (file.size / 1024 / 1024).toFixed(3);
      let status = "running"
      newFile.file_name = fileName;
      newFile.fileSize = fileSize;
      let file64 = await readFileAsync(files[i]);
      newFile.file_base64 = ("" + file64).substring(("" + file64).indexOf(',') + 1);
      newFile.status = status;
      that.uploadFileList.push(newFile)
      that.uploadFileList = [...that.uploadFileList]
      console.log(that.uploadFileList);
      if (i == files.length - 1) {
        that.uploadFileTask();
      }
      // };
    }

    that.isAddFileVisible = true;

  }
  uploadFileTask() {
    let itemId = sessionStorage.getItem('id');
    this.uploadFileList.forEach(file => {
      var param = {
        project_id: itemId,
        files: [{
          file_name: file.file_name,
          file_base64: file.file_base64
        }]
      }
      this.http.post('/contract-extraction/data-mgr/upload-files'
      , param).then((res: any) => {
        file.job_id = res.result.job_id;
      }).catch((err:any)=>{
        this.message.error(err.error_msg)
      })
    });

    this.getFileStatus();
  }


  getFileStatus() {
    console.log("开始查询");
    let that = this;
    this.jobTimer = setInterval(function name() {
      let fileList = [...that.uploadFileList]
      for (let i = 0; i < fileList.length; i++) {
        let file = fileList[i];
        if (file.status != "success" && file.status != "fail") {
          var param = {
            job_id: file.job_id
          }
          that.http.post('/contract-extraction/job-mgr/query-job', param).then((res: any) => {
            if (res.result.job_status == "success") {
              file.status = 'success'
              file.file_id = res.result.job_result.file_id;
              that.message.success("上传成功！");
            } else if (res.result.job_status == "timeout" || res.result.job_status == "fail") {
              file.status = 'fail'
              that.message.success("上传失败！");
            } else {
              file.status = 'running'
              if (file.percent) {
                if (file.percent < 99) {
                  file.percent++
                }
              } else {
                file.percent = 1;
              }

            }
          }).catch((err) => {
            that.message.error(err.error_msg);
          })
        } else {

        }
      }

      for (let i = 0; i < that.uploadFileList.length; i++) {
        for (let j = 0; j < fileList.length; j++) {
          if (that.uploadFileList[i].job_id == fileList[j].job_id) {
            that.uploadFileList[i].status = fileList[j].status;
            if (fileList[j].status == "success") {
              that.uploadFileList[i].file_id = fileList[j].file_id;
            }
          }
        }
      }
      that.uploadFileList = [...that.uploadFileList]
    }, 3000)
  }

  /*
  33酱:
  上传成功，只有删除能操作
  33酱:
  上传中的，走进度条，可以取消和删除
  33酱:
  上传失败的，可以重试和删除
   */
  restart(index) {
    if (this.uploadFileList[index].status != "fail") {
      return;
    }
    let itemId = sessionStorage.getItem('id');
    let file = this.uploadFileList[index];
    var param = {
      project_id: itemId,
      files: [{
        file_name: file.file_name,
        file_base64: file.file_base64
      }]
    }
    this.http.post('/contract-extraction/data-mgr/upload-files', param)
      .then((res: any) => {
        file.job_id = res.result.job_id;
        file.status = "running";
        this.uploadFileList[index] = file
      }).catch((err:any)=>{
        this.message.error(err.error_msg)
      })
  }

  cancel(index) {
    if (this.uploadFileList[index].status != "running") {
      return;
    }
    let that = this;
    let file = this.uploadFileList[index];
    var param = {
      job_id: file.job_id
    }
    this.http.post('/contract-extraction/job-mgr/cancel-upload-job', param).then((res: any) => {
      if (res.error_code == "AIS.0000") {
        // that.uploadFileList.splice(index, 1);
        file.status = "fail"
      }
    }).catch((err:any)=>{
      this.message.error(err.error_msg)
    })
  }

  delete(index) {
    let that = this;
    let file = this.uploadFileList[index];
    if (this.uploadFileList[index].status == "running") {
      const param = {
        job_id: file.job_id
      }
      this.http.post('/contract-extraction/job-mgr/cancel-upload-job', param).then((res: any) => {
        if (res.error_code == "AIS.0000") {
          that.uploadFileList.splice(index, 1);
        }
      })
    } else if (this.uploadFileList[index].status == "success") {
      const param = {
        file_id: file.file_id
      }
      this.http.post('/contract-extraction/data-mgr/delete-file', param).then((res: any) => {
        if (res.error_code == "AIS.0000") {
          that.uploadFileList.splice(index, 1);
        }
      })
    } else {
      that.uploadFileList.splice(index, 1);
    }
  }

  getIsCanRestart() {
    for (let i = 0; i < this.uploadFileList.length; i++) {
      if (this.uploadFileList[i].status == "fail") {
        return false;
      }
    }

    return true;
  }

  getIsCanCancel() {
    for (let i = 0; i < this.uploadFileList.length; i++) {
      if (this.uploadFileList[i].status == "running") {
        return false;
      }
    }
    return true;
  }

  restartAll() {
    if (this.getIsCanRestart()) {
      return;
    }
    this.restartAllShow = true;
  }

  hideRestartMode() {
    this.restartAllShow = false;
  }

  restartAllSubmit() {
    let itemId = sessionStorage.getItem('id');
    this.uploadFileList.forEach(file => {
      if (file.status == "fail") {
        var param = {
          project_id: itemId,
          files: [{
            file_name: file.file_name,
            file_base64: file.file_base64
          }]
        }

        this.http.post('/contract-extraction/data-mgr/upload-files', param).then((res: any) => {
          file.job_id = res.result.job_id;
        }).catch((err:any)=>{
          this.message.error(err.error_msg)
        })
      }
    });
  }

  hideCancelMode() {
    this.cancelAllShow = false;
  }

  cancelAll() {
    if (this.getIsCanCancel()) {
      return;
    }
    this.cancelAllShow = true;
  }

  cancelAllSubmit() {

    this.uploadFileList.forEach(file => {
      if (file.status == "running") {
        var param = {
          job_id: file.job_id
        }
        this.http.post('/contract-extraction/job-mgr/cancel-upload-job', param).then((res: any) => {
          if (res.error_code == "AIS.0000") {
            // that.uploadFileList.splice(index, 1);
            file.status = "fail"
          }
        }).catch((err:any)=>{
          this.message.error(err.error_msg)
        })
      }
    });
  }

  deletaAll() {
    this.deleteAllShow = true;
  }

  hideDeleteMode() { this.deleteAllShow = false; }

  deleteAllSubmit() {
    let that = this;
    this.uploadFileList.forEach(file => {
      if (file.status == "running") {
        var param = {
          job_id: file.job_id
        }
        this.http.post('/contract-extraction/job-mgr/cancel-upload-job', param).then((res: any) => {
          if (res.error_code == "AIS.0000") {
            // that.uploadFileList.splice(index, 1);
            file.status = "fail"
          }
        })
      } else if (file.status == "success") {
        const param = {
          file_id: file.file_id
        }
        this.http.post('/contract-extraction/data-mgr/delete-file', param).then((res: any) => {
          if (res.error_code == "AIS.0000") {
            // that.uploadFileList.splice(index, 1);
            file.status = "fail"
          }
        })
      }
    });

    this.uploadFileList = []; this.deleteAllShow = false;
  }


  cancelAdd() {
    if (!this.getIsCanCancel()) {
      this.modal.error({
        nzMask: false,
        nzTitle: `还有文件正在上传！`,
        nzContent: `还有文件正在上传！请小心关闭！`
      });
    } else {
      this.isAddFileVisible = false;
      this.uploadFileList = [];
      //在客户关闭上传文件框时，停止轮询
      if (this.jobTimer != null) {
        clearInterval(this.jobTimer);
      }
      this.getFileList();
    }
  }


  //通过job_id轮询查找file
  getFileDataByJob(job_id) {
    let that = this;
    that.clearTimer();
    that.fileTimer = setInterval(function () {
      var param = {
        job_id: job_id
      }
      that.http.post('/contract-extraction/job-mgr/query-job', param).then((res: any) => {
        if (res.result.job_status == "success") {

          that.clearTimer();
          that.fileListData = res.result.job_result;
          //这是实际接口 -- 测试时需要注销
          that.pdfData = [that.fileListData.content_base64];
          that.pdfSize = that.fileListData.page_size; // pdf的大小
          that.fileType = that.fileListData.file_type;
          //注销结束
          that.isSpinning = false;
          that.message.success("获取文件成功！");
        } else if (res.result.job_status == "timeout" || res.result.job_status == "fail") {
          that.clearTimer();
          that.message.error("获取文件失败，请重试");
        } else {

        }
      }).catch((err: any) => {
        that.clearTimer();
        that.message.error(err.error_msg);
      })
    }, 5000);
  }

  clearTimer() {
    console.log("1233")
    clearInterval(this.fileTimer);
  }

  getBlocksTxt(val) {
    let blocks = val;
    let ret = ''
    blocks.forEach(item => {
      ret += item.text;
    });
    return ret
  }

  //添加标注信息-value
  addBlock(itemIndex) {
    let valueId = "CMkj" + Date.parse(new Date().toString());
    this.fileTagData[itemIndex].values.push({ value_id: valueId, blocks: [], isCanBox: false });
  }

  //删除框选
  deleteBlock(itemIndex, blockIndex) {

    let that = this;
    console.log(that.fileTagData)
    if (that.fileTagData[itemIndex].values[blockIndex].value_id.indexOf('CMkj') < 0) {
      let param = {
        result_id: that.fileTagData[itemIndex].result_id,
        value_id: that.fileTagData[itemIndex].values[blockIndex].value_id
      };
      that.http
        .post('/contract-extraction/data-mgr/delete-value', param)
        .then((res: any) => {
          if (res.error_code == "AIS.0000") {
            console.log(that.fileTagData[itemIndex].values[blockIndex])
            that.fileTagData[itemIndex].values.splice(blockIndex, 1);
            console.log(that.fileTagData[itemIndex].values)
            that.updateHighBlocks();
            that.message.success("删除成功！");
          } else {
            that.message.error("删除失败！");
          }
        })
        .catch((err: any) => {
          that.message.error(err.error_msg)
        });
    } else {
      that.fileTagData[itemIndex].values.splice(blockIndex, 1);
      console.log(that.fileTagData[itemIndex].values)
      that.updateHighBlocks();
      that.message.success("删除成功！");
    }
    console.log(that.fileTagData)

  }
  //更新可以框选
  changeEdit(itemIndex, blockIndex) {
    this.fileTagData[itemIndex].values[blockIndex].isCanBox = true;
  }
  //框选PDF
  selectPdf(itemIndex, blockIndex) {
    console.log(itemIndex, blockIndex)
    this.isCanDraw = true;
    this.currBlock = {
      resultIndex: itemIndex, // value index
      blocksIndex: blockIndex // blocks index
    }
    // if ("isCanBox" in this.fileTagData[itemIndex].values[blockIndex] && this.fileTagData[itemIndex].values[blockIndex].isCanBox) {
    //   this.isCanDraw = true;
    //   this.currBlock = {
    //     resultIndex: itemIndex,
    //     blockIndex: blockIndex
    //   }
    // } else {
    //   this.message.error("请先点击修改按钮！");
    // }
  }

  HLChange(e) {
    console.log(e);
    let that = this;
    let loc = e[0].locations[0].location[0];
    let page = e[0].locations[0].page;
    var param = {
      "file_id": this.currFile.file_id,
      "location": loc,
      "page": page
    }
    console.log(param)
    console.log(that.fileTagData[that.currBlock.resultIndex]);
    that.http
      .post('/contract-extraction/data-mgr/get-ocr-result', param)
      .then((res: any) => {
        if (res.error_code == "AIS.0000") {
          // that.fileTagData[itemIndex].values.splice(blockIndex, 1);
          var block: any = {};
          block.text = res.result;
          block.update_text = res.result;
          block.location = loc;
          block.page = page;
          if (!that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks) {
            that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks = [];
          }
          that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks.push(block);
          //  that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blockIndex].blocks.push(block)
          console.log(that.fileTagData);
          that.updateHighBlocks();
          that.message.success("读取文本成功");
        } else {
          that.message.error("读取文本失败");
        }
      })
      .catch((err: any) => {
        console.log(err);
        that.message.error(err.error_msg)
      });
  }

  txtBlockChange(e) {
    let that = this;
    var block: any = {};
    block.text = e.text;
    block.update_text = e.text;
    block.location = [[e.startLoc, e.endLoc]];
    block.page = 0;

    if (!that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks) {
      that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks = [];
    }
    if (that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks.length < 1) {
      that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks.push(block);
    } else {
      that.fileTagData[that.currBlock.resultIndex].values[that.currBlock.blocksIndex].blocks[0] = block;
    }


    that.updateTxTBlocks();
    /*endLoc: 188
id: "7577e81d-19b8-b4dd-9335-8429f80285b9"
isOverlap: false
overlapId: ""
overlapType: ""
showEndLoc: 188
showStartLoc: 181
startLoc: 181
text: "歌斐诺宝 (上"
    */
    console.log(e);
  }

  saveBlocks(itemIndex, blockIndex) {
    let that = this;
    console.log(that.fileTagData[itemIndex])
    var param = {
      result_id: that.fileTagData[itemIndex].result_id,
      value_id: that.fileTagData[itemIndex].values[blockIndex].value_id.indexOf('CMkj') < 0 ? that.fileTagData[itemIndex].values[blockIndex].value_id : '',
      blocks: that.fileTagData[itemIndex].values[blockIndex].blocks
    }
    that.http
      .post('/contract-extraction/data-mgr/update-value', param)
      .then((res: any) => {
        if (res.error_code == "AIS.0000") {
          // that.fileTagData[itemIndex].values.splice(blockIndex, 1);
          that.fileTagData[itemIndex].values[blockIndex].value_id = res.result.value_id;
          that.message.success("更新标注结果成功！");
        } else {
          that.message.error("更新标注结果失败！");
        }
      })
      .catch((err: any) => {
        that.message.error(err.error_msg)
      });
  }

  changeBlocks(itemIndex, blocksIndex) {
    // this.fileTagData[itemIndex]
    this.fileTagData.forEach(fileData => {
      if (fileData.values) {
        fileData.values.forEach(blocks => {
          blocks.isCanEdit = false;
        });
      }
      // fileData.values.splice(blocksIndex, 1)
    });
    this.fileTagData[itemIndex].values[blocksIndex].isCanEdit = true;
    console.log(this.fileTagData)
  }

  deleteBlockNew(itemIndex, blocksIndex, blockIndex) {
    this.fileTagData[itemIndex].values[blocksIndex].blocks.splice(blockIndex, 1);
    this.updateHighBlocks();
  }

  tagSave() {
    let that = this;
    console.log(this.fileTagData);
    let param = {
      "file_id": this.currFile.file_id,
      labels_result: this.fileTagData
    }
    that.http
      .post('/contract-extraction/data-mgr/update-file-result', param)
      .then((res: any) => {
        if (res && res.error_code == "AIS.0000") {
          that.message.success("更新成功！")
        } else {
          that.message.success("更新失败！")
        }
      })
      .catch((err: any) => {
        console.log(err);
        that.message.error(err.error_msg)
      });
  }

  nextPage() {
    if (this.currentPage < this.allPages)
      this.targetPage = this.currentPage + 1;
    else
      this.message.error("已经是最后一页了！");
  }

  previousPage() {
    if (this.currentPage > 1) { this.targetPage = this.currentPage - 1; }
    else
      this.message.error("当前已经是第一页了！");
  }

  getCurrPage(e) {
    console.log("当前页面：", e);
    this.currentPage = e.curr;
    this.allPages = e.all;
  }

  pageChange(e) {
    console.log(e)
    console.log("currentPage", this.currPaginationPage);
    this.targetPage = e;
    console.log("targetPage", this.targetPage);
  }

  gotoPage(e) {
    console.log(e);
    this.targetPage = e;
  }

  //更改scale
  changePercent(e) {
    this.currScale = e;
    this.targetScale = this.currScale;
  }
  //放大
  addScale() {
    this.targetScale = this.currScale + 0.1;
  }
  //缩小
  subScale() {
    this.targetScale = this.currScale - 0.1;
  }
}
